package com.zero.util;

import com.zero.common.Common;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.*;
import java.util.Map;
import java.util.Objects;

/**
 * @author wuxi
 */
public class FreemarkerUtils {

    private FreemarkerUtils() {
    }

    public static void getTemplate(Template temp,
                                   Map<String, Object> map,
                                   String classPath,
                                   String separator) {
        Writer out;
        try {
            if (Objects.isNull(temp)) {
                throw new RuntimeException("Template 为null");
            }
            int i = classPath.lastIndexOf(separator);
            String filePath = classPath.substring(0,i);
            File path = new File(filePath);
            if (!path.exists() && !path.isDirectory()) {
                path.mkdirs();
            }

            File file = new File(classPath+ ".java");
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            temp.process(map, out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Template getTemplate(String templateName) {
        try {
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
            String templatePath = FreemarkerUtils.class.getResource(Common.separator_file_ios).getPath() + "templates";
            cfg.setDirectoryForTemplateLoading(new File(templatePath));
            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            cfg.setLogTemplateExceptions(false);
            return cfg.getTemplate(templateName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}